<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';

import {
  Button,
  InputSearch,
  message,
  Modal,
  Popconfirm,
  Dropdown,
  Menu,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter';
import { deleteDesignerApi, getDesignerApi, saveDesignerApi } from '#/api/core/designer';
import { $t } from '#/locales';
import { EllipsisOutlined } from '@ant-design/icons-vue';
import { type FieldConfig } from '#/api/core/lowcode';
import DesignerDrawer from './designer-drawer.vue';
import DesignIndex from './design-index.vue';
import RenderIndex from '../publish/single-page.vue';

interface DesignerModel {
  id?: number;
  name?: string;
  tableName?: string;
  layout?: string;
  redirect?: string;
  description?: string;
  context?: string;
  createBy?: string;
  updateBy?: string;
  createTimeFormat?: string;
  updateTimeFormat?: string;
}

const [BaseDrawer, baseDrawerApi] = useVbenDrawer({
  connectedComponent: DesignerDrawer,
});

function openNewDrawer() {
  baseDrawerApi.setData({});
  baseDrawerApi.open();
}

const searchText = ref('');
const selectedRows = ref<DesignerModel[]>([]);

const layoutOptions = {
  single: '单页布局',
  navigation: '导航布局',
  multi: '多条件布局',
};

const gridOptions: VxeGridProps<DesignerModel> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { field: 'redirect', title: '主页代码', width: 200 },
    { field: 'name', title: '菜单名称' },
    { field: 'tableName', title: '表名' },
    {
      field: 'layout',
      title: '布局',
      formatter: ({ cellValue }) => layoutOptions[cellValue as keyof typeof layoutOptions] || cellValue
    },
    { field: 'createByName', title: '创建人' },
    { field: 'updateByName', title: '修改人' },
    { field: 'createTimeFormat', title: '创建时间' },
    { field: 'updateTimeFormat', title: '最后修改时间' },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: $t('common.action.name'),
      width: 140,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getDesignerApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          search: searchText.value,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

async function deleteDesigner(row: DesignerModel) {
  try {
    await deleteDesignerApi(row.id!);
    await gridApi.reload();
    message.success($t('common.action.deleteSuccess'));
  } catch {
    message.error($t('common.submit.failed'));
  }
}

function editDesigner(row: DesignerModel) {
  baseDrawerApi.setData(row);
  baseDrawerApi.open();
}

function handleSave() {
  gridApi.reload();
}

function handleSearch() {
  gridApi.reload();
}

function handleDeleteSelected() {
  if (selectedRows.value.length === 0) return;

  const ids = selectedRows.value.map((row: DesignerModel) => row.id);

  Modal.confirm({
    title: $t('role.delete.title'),
    content: $t('role.delete.batchConfirm', { count: ids.length }),
    okText: $t('common.yes'),
    cancelText: $t('common.no'),
    async onOk() {
      await Promise.all(ids.filter((id): id is number => id !== undefined).map((id) => deleteDesignerApi(id)));
      selectedRows.value = [];
      gridApi.reload();
    },
  });
}

// 添加一个ref来控制显示内容
const showDesign = ref(false);
const currentRow = ref<DesignerModel | null>(null);

function designDesigner(row: DesignerModel) {
  currentRow.value = row;
  showDesign.value = true;
}

function previewDesigner(row: DesignerModel) {
  currentRow.value = row;
  // TODO: 实现预览逻辑
}

const gridEvents = {
  checkboxChange({ records }: { records: DesignerModel[] }) {
    selectedRows.value = records;
  },
  checkboxAll({ records }: { records: DesignerModel[] }) {
    selectedRows.value = records;
  },
};

// 修改处理设计器数据更新的函数
async function handleDesignerUpdate(updatedDesigner: DesignerModel) {
  try {
    await saveDesignerApi({
      ...updatedDesigner,
      id: currentRow.value?.id
    });

    // 更新当前行数据
    currentRow.value = updatedDesigner;

    // 可选：刷新列表数据
    await gridApi.reload();
  } catch (error) {
    console.error('保存失败:', error);
    message.error($t('common.action.saveFailed'));
  }
}

// 添加预览状态控制
const showPreview = ref(false);

// 修改处理预览返回的函数
function handlePreviewBack() {
  showPreview.value = false;  // 隐藏预览页面
  showDesign.value = true;    // 显示设计页面
}

// 添加预览数据的存储
const previewData = ref<{
  fields: FieldConfig[];
  tableName?: string;
  layout?: string;
  name?: string;
}>();

// 修改处理预览事件的函数
function handlePreview(data: {
  fields: FieldConfig[];
  tableName?: string;
  layout?: string;
  name?: string;
}) {
  previewData.value = data;
  showPreview.value = true;
  showDesign.value = false;
}
</script>

<template>
  <Page auto-content-height>
    <template v-if="!showDesign && !showPreview">
      <BaseDrawer :on-save="handleSave" />
      <Grid :grid-events="gridEvents">
        <template #toolbar-actions>
          <Button class="mr-2" type="primary" @click="openNewDrawer">
            {{ $t('common.action.add') }}
          </Button>
          <Button
            v-if="selectedRows.length > 0"
            class="ml-2"
            danger
            type="primary"
            @click="handleDeleteSelected"
          >
            {{ $t('common.action.delete') }}
          </Button>
        </template>
        <template #toolbar-tools>
          <InputSearch
            v-model:value="searchText"
            :placeholder="$t('common.search')"
            @search="handleSearch"
          />
        </template>
        <template #action="{ row }">
          <Button type="link" style="padding: 0 4px" @click="() => editDesigner(row)">
            {{ $t('common.action.edit') }}
          </Button>
          <Button type="link" style="padding: 0 4px" @click="() => designDesigner(row)">
            设计
          </Button>
          <Dropdown>
            <Button type="link" style="padding: 0 4px">
              <EllipsisOutlined />
            </Button>
            <template #overlay>
              <Menu>
                <Menu.Item key="preview" @click="() => previewDesigner(row)">
                  预览
                </Menu.Item>
                <Menu.Item key="delete">
                  <Popconfirm
                    :cancel-text="$t('common.no')"
                    :ok-text="$t('common.yes')"
                    :title="$t('role.delete.confirm')"
                    @confirm="() => deleteDesigner(row)"
                  >
                    <span style="color: red">{{ $t('common.action.delete') }}</span>
                  </Popconfirm>
                </Menu.Item>
              </Menu>
            </template>
          </Dropdown>
        </template>
      </Grid>
    </template>

    <template v-else-if="showDesign">
      <DesignIndex
        :designer="currentRow"
        v-model:show-design="showDesign"
        @update:designer="handleDesignerUpdate"
        @preview="handlePreview"
      />
    </template>

    <template v-else>
      <!-- 预览模式 -->
      <RenderIndex
        :fields="previewData?.fields"
        :table-name="previewData?.tableName"
        :layout="previewData?.layout"
        :name="previewData?.name"
        :is-preview="true"
        @back="handlePreviewBack"
      />
    </template>
  </Page>
</template>
